package simple

import (
	"fmt"
)

// https://leetcode-cn.com/problems/valid-parentheses/
// 有效的括号组合
// 算法: 直接通过栈，进行括号的组合

// 数据结构: 栈，协程不安全类型的
type CharStack struct {
	arr []int32
}

func NewStack() *CharStack {
	stack := new(CharStack)
	stack.arr = make([]int32, 0)
	return stack
}

func (stack *CharStack) Push(char int32) {
	stack.arr = append(stack.arr, char)
}

func (stack *CharStack) Pop() (int32, error) {
	currentLen := len(stack.arr)
	if currentLen == 0 {
		return 0, fmt.Errorf("stack size 0!")
	}
	toPopEle := stack.arr[currentLen-1]
	stack.arr = stack.arr[:currentLen-1]
	return toPopEle, nil
}

func (stack *CharStack) Size() int {
	return len(stack.arr)
}

func IsValid(s string) bool {
	myStack := NewStack()
	for _, currentChar := range s {
		switch currentChar {
		case '{', '[', '(':
			myStack.Push(currentChar)
		case '}', ']', ')':
			currentTopChar, err := myStack.Pop()
			if nil != err {
				return false
			}
			if !((currentTopChar == '(' && currentChar == ')') || (currentTopChar == '{' && currentChar == '}') ||
				(currentTopChar == '[' && currentChar == ']')) {
				return false
			}
		default:
			// 其他异常字符，也直接返回false
			return false
		}
	}
	if myStack.Size() != 0 {
		return false
	}
	return true
}
